﻿@inject ToastService Toast

<p>同时通过传递数据主键获取数据后再显示的例子组件</p>

<p>传递的参数主键为：@DataPrimaryId</p>

<p>通过传递参数获取的数据为：</p>

@if (Model != null)
{
    <ValidateForm Model="@Model" OnValidSubmit="@OnValidSubmit">
        <EditorForm TModel="Foo">
            <FieldItems>
                <EditorItem @bind-Field="@context.Id" Editable="false" />
                <EditorItem @bind-Field="@context.Hobby" Items="@Hobbys" />
            </FieldItems>
        </EditorForm>
        <div class="form-footer mt-3">
            <button type="button" class="btn btn-secondary" @onclick="@(e => OnClose?.Invoke())">
                <i class="fa fa-times"></i>
                <span>关闭</span>
            </button>
            <Button Color="Color.Primary" ButtonType="ButtonType.Submit" Icon="fa fa-save" Text="保存" />
        </div>
    </ValidateForm>
}

@code {
    [Inject]
    [NotNull]
    private IStringLocalizer<Foo>? Localizer { get; set; }

    [Parameter]
    public Action? OnClose { get; set; }

    [CascadingParameter(Name = "BodyContext")]
    private object? DataPrimaryId { get; set; }

    private Foo? Model { get; set; }

    [NotNull]
    private List<Foo>? Items { get; set; }

    [NotNull]
    private IEnumerable<SelectedItem>? Hobbys { get; set; }

    /// <summary>
    ///
    /// </summary>
    protected override void OnInitialized()
    {
        base.OnInitialized();

        Items = Foo.GenerateFoo(Localizer);
        Hobbys = Foo.GenerateHobbys(Localizer);
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();

        if (DataPrimaryId is int primaryId)
        {
            Model = Items.FirstOrDefault(i => i.Id == primaryId);
        }
    }

    private Task OnValidSubmit(EditContext model)
    {
        // do someting like save model into db
        OnClose?.Invoke();

        Toast?.Show(new ToastOption()
        {
            Title = "保存数据",
            Content = "保存成功，4 秒后自动关闭"
        });
        return Task.CompletedTask;
    }
}
